#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;

public class AttributeEditorTools
{
    public static FieldInfo GetFieldInfo(SerializedProperty property)  // 解决嵌套属性问题
    {
        if (property == null) return null;

        Type targetType = property.serializedObject.targetObject.GetType();
        string propertyPath = property.propertyPath;  // 获取属性路径  数组中：xx.Array.data[0].xx
        // 分割路径并移除数组相关部分
        string[] pathParts = propertyPath.Split('.');
        List<string> fieldNames = new List<string>();

        foreach (string part in pathParts)
        {
            // 跳过数组相关部分
            if (part == "Array" || part.StartsWith("data["))
                continue;

            fieldNames.Add(part);
        }

        // 如果没有有效的字段名，返回null
        if (fieldNames.Count == 0)
            return null;

        // 从目标类型开始，逐级获取字段信息
        Type currentType = targetType;
        FieldInfo fieldInfo = null;

        // 处理除最后一个字段外的所有字段（用于嵌套对象）
        for (int i = 0; i < fieldNames.Count - 1; i++)
        {
            fieldInfo = currentType.GetField(fieldNames[i],
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            if (fieldInfo == null)
                return null;

            currentType = fieldInfo.FieldType;

            // 如果是列表或数组，获取其元素类型
            if (currentType.IsGenericType && currentType.GetGenericTypeDefinition() == typeof(List<>))
            {
                currentType = currentType.GetGenericArguments()[0];
            }
            else if (currentType.IsArray)
            {
                currentType = currentType.GetElementType();
            }
        }

        // 获取最后一个字段
        string finalFieldName = fieldNames[fieldNames.Count - 1];
        fieldInfo = currentType.GetField(finalFieldName,
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        return fieldInfo;
    }
}
#endif